package club.ruanx.movie.service.impl;


import club.ruanx.acl.common.exception.UserException;
import club.ruanx.bean.PageBean;
import club.ruanx.core.service.base.BaseServiceImpl;
import club.ruanx.movie.entity.UserRate;
import club.ruanx.movie.repository.UserRateRepository;
import club.ruanx.movie.service.UserRateService;
import club.ruanx.security.bean.UserAuthInfoContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 阮胜
 * @date 2018/11/11 19:50
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserRateServiceImpl extends BaseServiceImpl<UserRate, String, UserRateRepository> implements UserRateService {

    @Override
    public UserRate rate(String movieId, Integer rate) throws UserException {
        String uid;
        try {
            uid = UserAuthInfoContextHolder.getCurrentUserAuthInfoThrow().getUid();
        } catch (UserException e) {
            throw new UserException("请先登录");
        }
        UserRate userRate = repository.findByUserIdAndMovieId(uid, movieId)
                .orElse(UserRate.builder().userId(uid).movieId(movieId).build());
        userRate.setRate(Float.valueOf(rate));
        return repository.save(userRate);
    }

    @Override
    public Page<UserRate> findAllByUserId(String uid, PageBean pageBean) {
        return repository.findAllByUserIdOrderByCreateTimeDesc(uid, pageBean.toPageable());
    }

}
